package com.kristin.guava;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class MainTest {


    public static class User {

        private Long id;

        private String name;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static User getUser(long id) {
        User user = new User();
        user.setId(id);
        user.setName("kristin" + id);
        return user;
    }

    private static final List<User> userList = new ArrayList<>();

    static {
        for (int i = 0; i < 10; i++) {
            userList.add(getUser(i));
        }
    }

    public static void main(String[] args) throws ExecutionException {
        LoadingCache<Long, User> activityTimingCache = CacheBuilder.newBuilder().initialCapacity(150)
                .expireAfterWrite(2, TimeUnit.SECONDS)
                .refreshAfterWrite(2, TimeUnit.SECONDS)
                .concurrencyLevel(5)
                .recordStats()
                .build(new CacheLoader<Long, User>() {
                    @Override
                    public User load(Long id) {
                        User hit = null;
                        for (User user : userList) {
                            if (user.getId().equals(id)) {
                                hit = user;
                                break;
                            }
                        }
                        return hit;
                    }
                });

        User user = activityTimingCache.get(11l);
        System.out.println(user.getId() + "---" +user.getName());

    }

}
